const axios = require('axios');

class WechatService {
  constructor() {
    this.appId = process.env.WECHAT_APPID;
    this.appSecret = process.env.WECHAT_SECRET;
    this.accessToken = null;
    this.tokenExpireTime = null;
  }

  // 获取access_token
  async getAccessToken() {
    // 检查token是否过期
    if (this.accessToken && this.tokenExpireTime && Date.now() < this.tokenExpireTime) {
      return this.accessToken;
    }

    try {
      const response = await axios.get('https://api.weixin.qq.com/cgi-bin/token', {
        params: {
          grant_type: 'client_credential',
          appid: this.appId,
          secret: this.appSecret
        }
      });

      if (response.data.errcode) {
        throw new Error(`获取access_token失败: ${response.data.errmsg}`);
      }

      this.accessToken = response.data.access_token;
      this.tokenExpireTime = Date.now() + (response.data.expires_in - 300) * 1000; // 提前5分钟过期

      return this.accessToken;
    } catch (error) {
      console.error('获取微信access_token错误:', error);
      throw error;
    }
  }

  // 生成小程序码（太阳码）
  async generateSunCode(scene, page) {
    try {
      const accessToken = await this.getAccessToken();
      
      const requestData = {
        scene: scene,
        width: 430,
        auto_color: false,
        line_color: { r: 0, g: 0, b: 0 },
        is_hyaline: false
      };

      // 如果指定了页面，则添加页面参数
      if (page) {
        requestData.page = page;
      }
      
      console.log('微信API请求参数:', {
        scene: scene,
        page: page,
        accessToken: accessToken ? '已获取' : '未获取'
      });
      
      const response = await axios.post(
        `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`,
        requestData,
        {
          responseType: 'arraybuffer',
          timeout: 10000 // 10秒超时
        }
      );

      // 检查响应头
      const contentType = response.headers['content-type'];
      console.log('微信API响应头:', contentType);
      
      // 检查是否返回错误
      if (!contentType || !contentType.includes('image/')) {
        const errorMsg = Buffer.from(response.data).toString('utf-8');
        console.error('微信API错误响应:', errorMsg);
        
        try {
          const errorData = JSON.parse(errorMsg);
          throw new Error(`生成小程序码失败: ${errorData.errmsg || errorData.errcode || '未知错误'}`);
        } catch (parseError) {
          throw new Error(`生成小程序码失败: ${errorMsg}`);
        }
      }

      // 将图片数据转换为base64
      const base64 = Buffer.from(response.data).toString('base64');
      return `data:image/jpeg;base64,${base64}`;
    } catch (error) {
      console.error('生成微信小程序码错误:', error);
      if (error.response) {
        console.error('错误响应状态:', error.response.status);
        console.error('错误响应头:', error.response.headers);
      }
      throw error;
    }
  }

  // 生成房间小程序码
  async generateRoomCode(roomCode, page) {
    try {
      // 使用房间号作为scene参数，微信限制scene最大32个字符
      const scene = roomCode;
      
      // 从环境变量获取页面路径，如果没有则不指定页面（跳转到首页）
      const pages = page||process.env.WECHAT_MINI_PROGRAM_PAGE;
      
      const sunCode = await this.generateSunCode(scene, pages);
      
      return {
        sunCode: sunCode,
        roomCode: roomCode,
      };
    } catch (error) {
      console.error('生成房间小程序码错误:', error);
      throw error;
    }
  }
}

module.exports = WechatService; 